var processNodeListJs = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.nextNodeList = new Array();
    this.jumpNodeList = new Array();
    this.shapeMap = new Map();
    this.connectList = new Map()
    this.shapeJsonMap = new Map();
    this.dropdownMap = new Map();
    this.init();
    return this;
};

processNodeListJs.prototype = {
    init: function () {
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        fieldArray.push({fieldName: "nextNodeList", defaultValue: []});
        fieldArray.push({fieldName: "jumpNodeList", defaultValue: []});
        fieldArray.push({fieldName: "processList", defaultValue: []});
        this.models = new bindBaseModel(null, fieldArray, null, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        //初始化下拉列表控件  this.nextNodeList  this.jumpNodeList
        this.initDropDownList(this.$parent.find("#nextTextNode"));
        this.initDropDownList(this.$parent.find("#jumpTextNode"));
        var that = this;
        this.$parent.find("#mainProcess").kendoDropDownList({
            dataTextField: "flowName",
            dataValueField: "id",
            select: function (e) {
                var item = this.dataItem(e.item);
                that.addElementToDiagram(item);
            }
        });
        this.initDiagram();
    },
    initDropDownList: function (nodeDiv) {
        nodeDiv.kendoDropDownList({
            dataTextField: "nodeName",
            dataValueField: "id"
        });
    },
    initDiagram: function (flowId) {
        var that = this;
        JsonpAjax(baseApiPath + "WfProcessNode/selectAll", null, function (result) {
            var dropDownList = that.$parent.find("#mainProcess").data("kendoDropDownList");
            var initDiagram = result.data[0];
            var initIndex = 0;
            for (var i = 0; i < result.data.length; i++) {
                that.dropdownMap.put(result.data[i]["id"], result.data[i]);
                if (isNotEmpt(flowId) && flowId == result.data[i]["id"]) {
                    initIndex = i;
                    initDiagram = result.data[i];
                }
            }
            that.sysUtils.mvvmModel.set("processList", result.data)
            dropDownList.select(initIndex);
            that.createDiagram(that.$parent.find("#processNodeGrid"));
            that.addElementToDiagram(initDiagram);
        });
        if (isEmpty(flowId)) {
            this.$parent.find("#save").bind("click", this, this.saveOrUpdateNode);
            this.$parent.find("#delete").bind("click", this, this.deleteNode);
            this.$parent.find("#saveNodeBtn").bind("click", this, this.saveNodeBtn);
        }
    },
    /**
     * 保存单个节点配置信息
     * @param e
     */
    saveNodeBtn: function (e) {
        var that = e.data; //全局JS
        var diagram = that.$parent.find("#processNodeGrid").getKendoDiagram();  //画布
        var dataItem = diagram.select()[0]["dataItem"];
        var nextNode = that.$parent.find("#nextTextNode").val();   //下一个节点
        var jumpNode = that.$parent.find("#jumpTextNode").val();   //跳转节点
        var shapeJson = that.shapeJsonMap.get(dataItem["id"]);
        var shapeDate = that.shapeMap.get(dataItem["id"]);
        if (isNotEmpt(shapeJson["nextNode"])) {   //如果之前存在关联，那么先去掉关联
//				diagram.remove(that.connectList.get(dataItem["id"] + "_x"));
            that.connectList.remove(dataItem["id"] + "_x");
        }
        if (isNotEmpt(nextNode)) {                   //不为空添加关联
            var conn = diagram.connect(that.shapeMap.get(dataItem["id"]), that.shapeMap.get(nextNode), {content: {text: "下一步"}});
            that.connectList.put(dataItem["id"] + "_x", {
                FromShapeId: dataItem["id"],
                ToShapeId: nextNode,
                Title: "下一步"
            });
        }
        if (isNotEmpt(shapeJson["jumpNode"])) {
//				diagram.remove(that.connectList.get(dataItem["id"] + "_t"));
            that.connectList.remove(dataItem["id"] + "_t");
        }
        if (isNotEmpt(jumpNode)) {
            var conn = diagram.connect(that.shapeMap.get(dataItem["id"]), that.shapeMap.get(jumpNode), {content: {text: "跳转"}});
            that.connectList.put(dataItem["id"] + "_t", {
                FromShapeId: dataItem["id"],
                ToShapeId: jumpNode,
                Title: "跳转"
            });
        }
        shapeJson["nextNode"] = nextNode;
        shapeJson["jumpNode"] = jumpNode;
        that.shapeJsonMap.put(dataItem["id"], shapeJson);
        shapeDate["dataItem"]["nextNode"] = nextNode;
        shapeDate["dataItem"]["jumpNode"] = jumpNode;
        that.shapeMap.put(dataItem["id"], shapeDate);
        that.loadDiagrmHtml(that.shapeJsonMap.values(), that.connectList.values());
    },
    /**
     * 添加元素到控件中
     */
    addElementToDiagram: function (result) {
        this.$parent.find("#processNodeGrid").find("div[data-role='toolbar']").remove();
        this.loadDiagrmHtml(result["processNodeList"], result["connectionList"]);
        //添加未纳入流程的节点
        var notProcessNodeList = result["notProcessNodeList"];
        var nodeDiv = this.$parent.find("#nodeDiv");
        nodeDiv.empty();
        for (var i = 0; i < notProcessNodeList.length; i++) {
            this.addNotProcessNode(nodeDiv, notProcessNodeList[i])
        }
    },
    /**
     * 添加未纳入流程的节点
     */
    addNotProcessNode: function (nodeDiv, notProcessNode) {
        var node = $("<div class='pnNodebtn'>" + notProcessNode["nodeName"] + "</div>");
        node.data("json", notProcessNode);
        nodeDiv.append(node);
        //添加左侧未纳入流程节点配置菜单拖拽功能
        node.bind("dblclick", this, this.addDiagramNode);
    },
    /**
     * 加载Diagrm控件元素
     */
    loadDiagrmHtml: function (processNodeList, connectionList) {
        var kendoDiagram = this.$parent.find("#processNodeGrid").getKendoDiagram();
        //先清理掉控件中的元素
        kendoDiagram.clear();
        this.shapeMap.clear();
        this.connectList.clear();
        this.shapeJsonMap.clear();
        this.nextNodeList = new Array();
        this.jumpNodeList = new Array();
        //在添加新的元素
        var p = null;
        var shape = null;
//			var connection = null;
        for (var i = 0; i < processNodeList.length; i++) {
            p = processNodeList[i];
            shape = kendoDiagram.addShape({x: p["positionX"], y: p["positionY"], dataItem: p});
            this.shapeMap.put(p["id"], shape);
            this.shapeJsonMap.put(p["id"], p);
            //添加可下拉列表框的流程节点
            this.nextNodeList.push(p);
            this.jumpNodeList.push(p);
        }
        this.sysUtils.mvvmModel.set("nextNodeList", this.nextNodeList);
        this.sysUtils.mvvmModel.set("jumpNodeList", this.jumpNodeList);
        for (var i = 0; i < connectionList.length; i++) {
            kendoDiagram.connect(this.shapeMap.get(connectionList[i]["FromShapeId"]), this.shapeMap.get(connectionList[i]["ToShapeId"]),
                {content: {text: connectionList[i]["Title"]}});
            var type = connectionList[i]["Title"] == "下一步" ? "x" : "t";
            this.connectList.put(connectionList[i]["FromShapeId"] + "_" + type, connectionList[i]);
        }
    },
    /**
     * 非列入标签双击后进入画布
     * @param e
     */
    addDiagramNode: function (e) {
        var that = e.data; //全局JS
        var nodeJson = $(this).data("json"); //当前双击的节点
        var diagram = that.$parent.find("#processNodeGrid").getKendoDiagram();  //画布
        var shape = diagram.addShape({x: 300, y: 50, dataItem: nodeJson});
        that.shapeMap.put(nodeJson["id"], shape);
        that.shapeJsonMap.put(nodeJson["id"], nodeJson);
        $(this).remove();
        that.nextNodeList.push(nodeJson);
        that.jumpNodeList.push(nodeJson);
        that.sysUtils.mvvmModel.set("nextNodeList", that.nextNodeList);
        that.sysUtils.mvvmModel.set("jumpNodeList", that.jumpNodeList);
    },
    /**
     * 删除节点
     */
    deleteNode: function (e) {
        var that = e.data; //全局JS
        var diagram = that.$parent.find("#processNodeGrid").getKendoDiagram();  //画布
        var shapeList = diagram.select();
        var nodeDiv = that.$parent.find("#nodeDiv");
        for (var i = 0; i < shapeList.length; i++) {
            var nodeId = shapeList[i]["dataItem"]["id"];
            if (isNotEmpt(nodeId)) {  //表示选中的是节点
                that.connectList.remove(nodeId + "_x");
                that.connectList.remove(nodeId + "_t");
                that.shapeMap.remove(nodeId);
                var shapeNode = that.shapeJsonMap.get(nodeId);
                shapeNode["jumpNode"] = "";
                shapeNode["nextNode"] = "";
                that.addNotProcessNode(nodeDiv, shapeNode);
                that.shapeJsonMap.remove(nodeId);
            } else {   //选中的是线条
                var formId = shapeList[i]["dataItem"]["from"];
                var type = shapeList[i]["options"]["content"]["text"] == "下一步" ? "x" : "t";
                var fieldName = type == "t" ? "jumpNode" : "nextNode";
                var shape = that.shapeMap.get(formId);
                if (null != shape) {
                    shape["dataItem"][fieldName] = "";
                }
                var json = that.shapeJsonMap.get(formId);
                if (null != json) {
                    json[fieldName] = "";
                }
                that.connectList.remove(formId + "_" + type);
                that.shapeMap.remove(formId);
            }
        }
        that.loadDiagrmHtml(that.shapeJsonMap.values(), that.connectList.values());
    },
    createDiagram: function (div, result) {
        var that = this;
        div.kendoDiagram(
            {
                dataSource: new kendo.data.HierarchicalDataSource(
                    {
                        data: []
                    }),
                connectionsDataSource: new kendo.data.HierarchicalDataSource(
                    {
                        data: []
                    }),
                layout: {
                    type: "tree",
                    subtype: "right"
                },
                shapeDefaults: {
                    visual: this.visualTemplate,
                    editable: {
                        drag: true,
                        tools: false
                    }
                },
                connectionDefaults: {
                    stroke: {
                        color: "#979797",
                        width: 2
                    },
                    endCap: {
                        type: "ArrowEnd",
                        fill: {
                            color: "#a3a3a3"
                        },
                        stroke: {
                            color: "#a3a3a3",
                            width: 2
                        }
                    },
                    editable: {
                        drag: false,
                        tools: false
                    }
                },
                select: function (e) {
                    //取消选择节点显示节点属性
                    if (e.deselected.length) {
                        that.$parent.find(".entryFlowPop").stop().animate({top: "-220px"}, 1000);
                    }
                },
                click: function (e) {
                    if (isNotEmpt(e.item.dataItem.id)) {
                        that.$parent.find(".entryFlowPop").stop().animate({top: "0"}, 1000);
                        var dataItem = e.item.dataItem;
                        that.$parent.find("#nodeTextName").val(dataItem["nodeName"]);
                        that.sysUtils.mvvmModel.set("nextNode", dataItem["nextNode"]);
                        that.sysUtils.mvvmModel.set("jumpNode", dataItem["jumpNode"]);
                    }
                },
                dragEnd: function (e) {
                    var shape = e.shapes[0];
                    var shapeJson = that.shapeJsonMap.get(shape.dataItem.id);
                    shapeJson["positionX"] = shape._bounds.x;
                    shapeJson["positionY"] = shape._bounds.y;
                    that.shapeJsonMap.put(shape.dataItem.id, shapeJson);
                }
            });
    },
    visualTemplate: function (options) {
        var dataviz = kendo.dataviz;
        var g = new dataviz.diagram.Group();
        var dataItem = options.dataItem;
        g.append(new dataviz.diagram.Rectangle({
            width: 150,
            height: 50,
//				x:dataItem.positionX,
//				y:dataItem.positionY,
            stroke: {
                width: 0
            },
            fill: {
                gradient: {
                    type: "linear",
                    stops: [{
                        color: "red",
                        offset: 0,
                        opacity: 0.5
                    }, {
                        color: "red",
                        offset: 1,
                        opacity: 1
                    }]
                }
            }
        }));
        g.append(new dataviz.diagram.TextBlock({
            text: dataItem.nodeName,
            x: 20,
            y: 15,
            fill: "#fff"
        }));
        return g;
    },
    /**
     * 打开编辑按钮
     */
    openEdit: function () {
        var _this = this;
        var flowChartId = _this.$parent.find("#mainProcess").data("kendoDropDownList").value();
        JsonpAjax(baseApiPath + 'processNode/findProcessNodeById?flowChartId=' + flowChartId, undefined, 'json', function (res) {
            _this.entity = res;
            _this.editDiv = _this.sysUtils.openWindow(_this.editDiv, {
                title: "编辑流程节点",
                height: "520px",
                width: "800px",
                resizable: false,
                content: "views/parkLotCenter/processNode/processNodeEdit.html",
            }, true);
        }, true);
    },
    /**
     * 保存或修改节点流程配置
     * @param e
     */
    saveOrUpdateNode: function (e) {
        var that = e.data; //全局JS
        var flowId = that.$parent.find("#mainProcess").val();
        var dataItems = that.shapeJsonMap.values();
//			var dataItems = new Array();
//			var dataItem = null;
//			for(var i = 0;i<shapeVal.length;i++){
//			dataItem = shapeVal[i]["dataItem"];
//			dataItem["positionX"] = shapeVal[i]["_bounds"]["x"];
//			dataItem["positionY"] = shapeVal[i]["_bounds"]["y"];
//			dataItems.push(dataItem);
//			}
        JsonpAjax(baseApiPath + 'WfProcessNode/saveOrUpdate/' + flowId, JSON.stringify(dataItems), function (res) {
            that.initDiagram(flowId);  //重新加载下拉列表
        });
    }

};


var processNodeEditJs = function (target) {
    this.target = target;
    this.init();
    return this;
};

processNodeEditJs.prototype = {
    init: function () {
        this.target.find("#title").text(processNodeJs.entity["flowName"]);
        this.createDiagram(this.target.find("#processNodeList"), processNodeJs.entity);
        this.target.find("#processNodeList").find("div[data-role='toolbar']").remove();
        var json = [{name: "下一节点", code: "0"}, {name: "跳转节点", code: "1"}];
        Utils.createAjaxDropDownList({div: this.target.find('#connType'), select: json, unshift: true});
        //添加未纳入流程的节点
        var notProcessNodeList = processNodeJs.entity["notProcessNodeList"];
        var nodeDiv = this.target.find("#nodeDiv");
        for (var i = 0; i < notProcessNodeList.length; i++) {
            var node = $("<div class='pnNodebtn'>" + notProcessNodeList[i]["nodeName"] + "</div>");
            node.data("json", notProcessNodeList[i]);
            nodeDiv.append(node);
        }


    },
    /**
     * 创建层级节点显示图(带拖拽加线功能)
     * @param div
     * @param result
     */
    createDiagram: function (div, result) {
        var rsDiv = $("<div id='" + result["id"] + "' style='width:100%;height:100%;'></div>");
        div.append(rsDiv);
        rsDiv.kendoDiagram(
            {
                dataSource: new kendo.data.HierarchicalDataSource(
                    {
                        data: result["processNodeList"],
                        schema: {
                            model: {
                                id: "id",
                                fields: {
                                    fromX: {
                                        from: "positionX",
                                        type: "number"
                                    },
                                    fromY: {
                                        from: "positionY",
                                        type: "number"
                                    }
                                }
                            }
                        }
                    }),
                connectionsDataSource: new kendo.data.HierarchicalDataSource(
                    {
                        data: result["connectionList"],
                        schema: {
                            model: {
                                id: "id",
                                fields: {
                                    id: {
                                        from: "id",
                                        type: "String",
                                        editable: false
                                    },
                                    from: {
                                        from: "FromShapeId",
                                        type: "String"
                                    },
                                    to: {
                                        from: "ToShapeId",
                                        type: "String"
                                    },
                                    title: {
                                        from: "Title",
                                        type: "String"
                                    }
                                }
                            }
                        }
                    }),
                layout: {
                    type: "force",
                    subtype: "down"
                },
                shapeDefaults: {
//											visual : this.visualTemplate,
                    editable: {
                        tools: ["delete"]
                    },
                    content: {
                        template: "#:dataItem.nodeName#"
                    }
                },
                connectionDefaults: {
                    stroke: {
                        color: "#979797",
                        width: 2
                    },
                    content: {
                        template: "#:dataItem.title#"
                    },
                    editable: {
                        tools: ["delete"]
//											connectionTemplate: kendo.template($("#popup-editor").html())
                    },
                    endCap: {
                        type: "ArrowEnd",
                        fill: {
                            color: "#a3a3a3"
                        },
                        stroke: {
                            color: "#a3a3a3",
                            width: 2
                        }
                    }
                },
                editable: true,
                remove: function (e) {
                    debugger;
                },
                select: function (e) {
                    debugger;
                }
            });
    },
    visualTemplate: function (options) {
        var dataviz = kendo.dataviz;
        var g = new dataviz.diagram.Group();
        var dataItem = options.dataItem;
        g.append(new dataviz.diagram.Rectangle({
            width: 150,
            height: 50,
//				x:dataItem.positionX,
//				y:dataItem.positionY,
            stroke: {
                width: 0
            },
            fill: {
                gradient: {
                    type: "linear",
                    stops: [{
                        color: "red",
                        offset: 0,
                        opacity: 0.5
                    }, {
                        color: "red",
                        offset: 1,
                        opacity: 1
                    }]
                }
            }
        }));
        g.append(new dataviz.diagram.TextBlock({
            text: dataItem.nodeName,
            x: 20,
            y: 15,
            fill: "#fff"
        }));
        return g;
    }
};